<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/8/18
 * Time: 11:15
 */

namespace app\logic\cron;


use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\common\lib\GuzzleNew;
use app\common\lib\TencentCos;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\novel\NovelChapterModel;
use app\model\novel\NovelChapterPartModel;
use app\model\novel\NovelSpreadModel;
use app\model\novel\NovelSpreadUnderWaterModel;
use support\Db;

class QiCatLogic extends BaseLogic
{
    protected static $instance;

    protected $insertTaskDatas;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if (is_object(self::$instance)) {
//            return self::$instance;
//        }

        return  new self();
    }

    public function getNovelList()
    {
        $page=50;
        $size = 100;
        $businessId = 777;
        while ($page){
            $param = [
                'page'=>$page,
                'page_size'=>$size,
                'product_id'=>1,
            ];
            $path = 'api/v1/data/book/index?'.http_build_query($param);
            $header = [
                'X-Qm-Devops-Token'=>config('param.qi_cat_token')
            ];
            $result = (new GuzzleNew())->get('https://kol.wtzw.com/',$path,$header);

            if($result['code']!=200){
                throw new IndexException(4020,$result['message']);
            }

            //var_dump($page,$result['data']['page_data']);
            if(!empty($result['data']['list'])){
                $data = $result['data']['list'];
                $data = array_reverse($data);
                $bookIds = array_column($data,'book_id');
                $where = ['business_id'=>$businessId,['book_id','in',$bookIds],'isdel'=>0];
                $hasBookIds = NovelSpreadModel::getInstance()->getWhere($where)->pluck('book_id')->toArray();

                foreach($data as $val){
                    $this->autoCreateTableAndInsertData(
                        [
                            'table'         => 'video_qi_cat_novel_list',
                            'keyid'         => 'qicat_novel_list_id',
                            'attributes'    => $val,
                            'update_fields' => ['book_id'],
                        ]
                    );

                    if(in_array($val['book_id'],$hasBookIds)==false){
                        $mainImageFileName = substr(md5(uniqid().time()),-26).'.jpg';
                        try{
                            $res = TencentCos::getInstance()->uploadLocalFile($val['cover'],'qicat/novel',$mainImageFileName);
                            if(isset($res['Location'])){
                                $mainImage = 'https://'.$res['Location'];
                            }
                        }catch (\Exception $e){}

                        $maxId =  NovelSpreadModel::getInstance()->getWhere([['novel_sn','>',0]])->max('novel_sn');
                        $novelSn = Common::getSnCode($maxId,'50',3,1);
                        $insert = [
                            'novel_sn'=>$novelSn,
                            'title'=>$val['book_name']??'',
                            'main_image'=>$mainImage??'',
                            'business_id'=>$businessId,
                            'labels'=>implode(',',($val['tags']??[])),
                            'desc'=>$val['intro'],
                            'data_source_key'=>'video_qi_cat_novel_list',
                            'data_source_id'=>$val['book_id'],
                            'start_time'=>date('Y-m-d H:i:s'),
                            'first_category'=>$val['first_category'],
                            'second_category'=>$val['second_category'],
                            'words_num'=>$val['words_num'],
                            'operate_tags'=>implode(',',($val['tags']??[])),
                            'author'=>$val['author'],
                            'book_id'=>$val['book_id'],
                            'status'=>0,
                            'spread_type'=>2,
                            'under_status'=>1,
                            'platform'=>4,
                            'lang'=>'cn',
                        ];
                        $id = NovelSpreadModel::getInstance()->saveData($insert);

                        //todo 2 获取前5章节内容
                        $param2 = [
                            'book_id'=>$val['book_id'],
                            'product_id'=>1,
                        ];
                        $path2 = 'api/v1/data/book/chapters?'.http_build_query($param2);
                        $header2 = [
                            'X-Qm-Devops-Token'=>config('param.qi_cat_token')
                        ];
                        $result2 = (new GuzzleNew())->get('https://kol.wtzw.com/',$path2,$header2);
                        //var_dump($result2['data']['content']);
                        if(!empty($result2['data']['content'])){
                            $contents = explode("\n",$result2['data']['content']);
                            $contents = array_slice($contents,0,500);
                            $insert2 = [
                                'novel_sn'=>$novelSn,
                                'number'=>1,
                                'name'=>$val['book_name'].'-前5章内容',
                                'original_content'=>implode("\n",$contents),
                                'spread_type'=>2,
                                'lang'=>'cn',
                            ];
                            NovelChapterModel::getInstance()->insert($insert2);
                        }
                    }
                }
            }

            $page--;
            sleep(1);
        }

        //超过半个小时没有更新，则是下架
        $bookIds = Db::table('video_qi_cat_novel_list')->where('created_at','<',date('Y-m-d 00:00:00',strtotime('-2 day')))->pluck('book_id')->toArray();
        $bookIds && NovelSpreadModel::getInstance()->getWhere(['business_id'=>$businessId,['book_id','in',$bookIds]])->update(['under_status'=>2,'status'=>0]);

        return ['success'];
    }

    public function updateNovelByUpload()
    {
        $where = [
            'data_source_key' => 'excel',
            'data_source_id'  => 0,
            'business_id'     => 777,
            ['main_image', '=', ''],
            'isdel'           => 0
        ];
        $novelData = NovelSpreadModel::getInstance()->getWhere($where)->get();
        $heads = [
            'Cookie'=>'UA=hqJWmqnj43dUtT9Kiou1BzkDuEgKh2FKgh97gIjKRl27NTFbH_KlNa-KFCswByRCpqGtmCFDNhgEtTglHaxt3okNhawKBy2vp3s_pqNvBL-KFlxLBlU2te0LNLrwtT97gash4qpxOz-DNhgEtTgl; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22190ee7b47cba1b-085c0167980e0c-26001e51-2073600-190ee7b47ccfb7%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22https%3A%2F%2Fx0sgcptncj.feishu.cn%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkwZWU3YjQ3Y2JhMWItMDg1YzAxNjc5ODBlMGMtMjYwMDFlNTEtMjA3MzYwMC0xOTBlZTdiNDdjY2ZiNyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%22190ee7b47cba1b-085c0167980e0c-26001e51-2073600-190ee7b47ccfb7%22%7D; acw_tc=2760826a17243001100358025ebde16d32c104c03b20dee2790e45ab771760',
            'user-agent'=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
        ];
        $ids = [];
        foreach ($novelData as $val){
            $url = 'api/v1/h5/adapt-reader?book_id='.$val['book_id'];
            $result = (new GuzzleNew())->get('https://api-bc.wtzw.com/',$url,$heads);
            if(!empty($result['data'])){
                $mainImageFileName = substr(md5(uniqid().time()),-26).'.jpg';
                $mainImage = '';
                try{
                    $res = TencentCos::getInstance()->uploadLocalFile($result['data']['cover'],'qicat/novel',$mainImageFileName);
                    if(isset($res['Location'])){
                        $mainImage = 'https://'.$res['Location'];
                    }
                }catch (\Exception $e){}

                $val->title = $result['data']['title'].'(短)';
                $val->author = $result['data']['author'];
                $val->words_num = $result['data']['words_num'];
                $val->desc = $result['data']['intro'];
                $val->main_image = $mainImage??'';
                $val->save();
                if(!empty($result['data']['chapter_list'])){
                    foreach($result['data']['chapter_list'] as $k=>$chapter){
                        $insert2 = [
                            'novel_sn'=>$val['novel_sn'],
                            'number'=>$chapter['index'],
                            'name'=>$chapter['title'],
                            'original_content'=>$chapter['chapter_content'],
                            'spread_type'=>2,
                            'lang'=>'cn',
                        ];
                        NovelChapterModel::getInstance()->insert($insert2);
                    }
                }
                $ids[] = $val['id'];
            }
            sleep(1);
        }

        return $ids;
    }
}